Pythonic Programming by Dmitry Zinoviev

Pythonic Programming by Dmitry Zinoviev

Author:Dmitry Zinoviev [Dmitry Zinoviev]
Language: eng
Format: epub
Publisher: Pragmatic Bookshelf
Published: 2021-09-23T00:00:00+00:00


Tip 52 Let the Caller Print

★★2.7, 3.4+ Functions or methods are usually considered as units of computation. They take the arguments (or rely on global variables, see Tip 92, ​Remember, There Are No Globals​), apply your algorithms to them, compute the results, and return them to the caller. If a function prints the calculated result instead of returning it, the caller cannot use the result for further computations. Moreover, the caller may be duped to believe that what the function returns is the result (see Tip 50, ​Make Functions Always Return Something​), but it is not. Here is a wrong way to produce a result:

​ ​def​ ​add1​(x):

​ ​print​(x+1)

​ ​# There is an implicit return None on this line!​

​ y = add1(10)

​=> ​11​

​ ​print​(y)

​=> ​None​

Here is a right way:

​ ​def​ ​add1​(x):

​ ​return​ x+1

​ y = add1(10)

​ ​print​(y)

​=> ​11​

Aside from the right and wrong ways, there is also a questionable way when a function prints the result and then returns it:

​ ​def​ ​add1​(x):

​ ​print​(x+1)

​ ​return​ x+1

​ y = add1(10)

​=> ​11​

​ ​print​(y)

​=> ​11​

This function, while functionally correct, combines computation and presentation. It always displays the result (and perhaps some other messages) and returns the result to the caller. The caller has no control over the function’s printout. Since printing is slow (see Tip 63, ​Build, Then Print​), if you call a “talkative” function in a loop, the performance of your code may significantly degrade. Also, it may be hard to see essential results buried in the sea of chatter. Let the caller of the function decide whether the returned value is worth printing.

You may still want to have an option of printing the result before returning it (say, for a very legitimate purpose of debugging). Do so by making printing optional and controllable by the caller, as explained in Tip 55, ​Pass Arguments Your Way​:

​ ​def​ ​add1​(x, debug=None):

​ ​if​ debug:

​ ​print​(x+1)

​ ​return​ x+1

​ y = add1(10)

​ y = add1(10, True)

​=> ​11​

​ ​print​(y)

​=> ​11​

As a side note, when you enable printing within a function, add an explanatory message to each printout:

​ ​print​(f​'This is x+1 in function add1: {x+1}'​)



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Popular ebooks
Eco-friendly approach of bio-indigo synthesis and developing purification methods towards isolation of indigo from indirubin and bacterial fragments by Ramalingam Manivannan & Kaliyan Prabakaran & Young-A Son(232852)
Personalized inhaled bacteriophage therapy for treatment of multidrug-resistant Pseudomonas aeruginosa in cystic fibrosis by unknow(201359)
CONSORT 2025 statement: updated guideline for reporting randomized trials by unknow(102427)
Critical evaluation of the ProfiLER-02 study design and outcomes by Vivek Subbiah & Razelle Kurzrock(101962)
Cardiac gene therapy makes a comeback by Oliver J. Müller & Susanne Hille & Anca Kliesow Remes(101760)
Whisky: Malt Whiskies of Scotland (Collins Little Books) by dominic roskrow(74559)
Unveiling the design rules for tunable emission in graphene quantum dots: A high-throughput TDDFT and machine learning perspective by Şener Özönder & Mustafa Coşkun Özdemir & Caner Ünlü(50973)
A yeast-based oral therapeutic delivers immune checkpoint inhibitors to reduce intestinal tumor burden by unknow(40345)
Covalent hitchhikers guide proteins to the nucleus by Alexander F. Russell & Madeline F. Currie & Champak Chatterjee(40269)
Meet the Authors: Christopher R. Mansfield and Emily R. Derbyshire by Christopher R. Mansfield & Emily R. Derbyshire(40170)
Alkaline-earth metals promote propane dehydrogenation with carbon dioxide through geometric effects: Altering the reaction pathway by unknow(32795)
Induced iron vacancies boosting FeOOH loaded on sustainable Fenton-like collagen fiber membrane for efficient removal of emerging contaminants by unknow(32589)
Efficient electric-field-assisted photochemical conversion of methane to n-propanol exclusively over penetrated TiO2Ti hollow fibers by Guanghui Feng(32509)
Bi2SiO5 nanosheets as piezo-photocatalyst for efficient degradation of 2,4-Dichlorophenol by Hangyu Shi & Yifu Li & Lishan Zhang & Guoguan Liu & Qian Zhang & Xuan Ru & Shan Zhong(32450)
A novel NDIPTA organic heterojunction photocatalyst with built-in electric field for efficient hydrogen production by Jiahui Yang & Baojun Ma & Yongfa Zhu(32421)
Enhanced conversion of methane to liquid-phase oxygenates via hollow ferrite nanotube@horseradish peroxidase based photoenzymatic catalysis by Jun Duan & Shiying Fan & Xinyong Li & Shaomin Liu(32388)
Ordered macroporous superstructure of defective carbon adorned with tiny cobalt sulfide for selective electrocatalytic hydrogenation of cinnamaldehyde by Xiao-Shi Yuan & Sheng-Hua Zhou & San-Mei Wang & Wenbo Wei & Xiaofang Li & Xin-Tao Wu & Qi-Long Zhu(32307)
What's Done in Darkness by Kayla Perrin(27220)
Topological analysis of non-conjugated ethylene oxide cored dendrimers decorated with tetraphenylethylene: Insights from degree-based descriptors using the polynomial approach by A Theertha Nair & D Antony Xavier & Annmaria Baby & S Akhila(26600)
Investigation of mechanical and self-healing properties of hydroxyl-terminated polybutadiene functionalized with 2-ureido-4-pyrimidinone by Mohsen Kazazi & Mehran Hayaty & Ali Mousaviazar(26522)